<?php

class mobileapi_rpc_starbuy_special{

    function __construct(){
        $this->mdl_special_goods = app::get('starbuy')->model('special_goods');
        $this->mdl_product = app::get('b2c')->model('products');
        $this->mdl_goods = app::get('b2c')->model('goods');
        $this->userObject = kernel::single('b2c_user_object');
        $this->special_pro = kernel::single('starbuy_special_products');
    }
    function index($params=array()){
        $type_id = $params['type_id'];
        $page = $params['page'];
        $GLOBALS['runtime']['path'] = $this->runtime_path($type_id);
        $page = $page ? $page : 1;
        $params = $this->filter_decode('',$type_id);
        $filter = $params['filter'];
        $orderby = $params['orderby'];
        $beabout = $this->get_product($filter,$page,$orderby);
//        $released = $this->get_released_product($filter);
        return $beabout;
    }


    function runtime_path($type_id,$product_id=null){
        $title = kernel::single('starbuy_special_products')->getTypename(array('type_id'=>$type_id));

        $url = "#";
        if($product_id){
            $url = $this->gen_url(array('app'=>'starbuy', 'ctl'=>'site_special','act'=>'index','arg0'=>$type_id));
        }
        $path = array(
            array(
                'type'=>"goodscat",
                'title'=>"首页",
                'link'=>kernel::base_url(1),

            ),
            array(
                'type'=>"goodscat",
                'title'=>$title,
                'link'=>$url,
            ),
        );

        if($product_id){
            $product = $this->_getProduct($product_id);
            $path[] = array(
                'type'=>"goodscat",
                'title'=>$product['name'],
                'link'=>"#",
            );
        }
        return $path;
    }
    function get_product($filter,$page=1,$orderby="promotion_price asc"){

        $filter['release_time|sthan']=time();
        $filter['end_time|bthan']=time();
        $filter['status']="true";
        //分页
//        $filter = array();
        $pageLimit = $_POST['limit'];
        $pageLimit = ($pageLimit ? $pageLimit : 4);
        //获取参加团购的货品
        $special_goods = $this->mdl_special_goods->getGList("*",$filter,$pageLimit*($page-1),$pageLimit,$orderby);
        $ruleModel = app::get('starbuy')->model('special');
        $adtypeModel = app::get('mobileapi')->model('indexad_group');
        $adModel = app::get('mobileapi')->model('indexad');
        if($filter['type_id'] == 1){
            $showtype = 'groupbuy_ad';
        }else{
            $showtype = 'second_ad';
        }
        $res = $adtypeModel->getRow('group_id',array('showtype'=>$showtype));
        $res = $adModel->getlist('*',array('group_id'=>$res['group_id']));
        $ads = false;
        foreach($res as $k=>$v){
            $ads[$v['group_name']] = $v;
        }
        $tmp_rule = '';
        foreach($special_goods as $value){
            $tmp = $this->special_pro->getParams($value);
            $tmp['img'] = $v['img'] = kernel::single('base_storager')->image_path($tmp['image_default_id'],'m');
            $rule = $ruleModel->getRow('images',array('special_id'=>$value['special_id']));
            $tmp['store'] = $this->mdl_goods->dump($tmp['goods_id'],'store');
            $tmp['store'] = $tmp['store']['store'];
            if($filter['type_id'] == 2){
                $result[$value['begin_time']]['images'] = $rule['images'];
                $result[$value['begin_time']]['goods'][] = $tmp;
                $result[$value['begin_time']]['time']['begin'] = $value['begin_time'];
                $result[$value['begin_time']]['time']['end'] = $value['end_time'];
            }else{
                $result['goods'][] = $tmp;
                $result['images'] = $rule['images'];
            }
        }
        $result['ads'] = $ads;
        return $result;
    }

    function get_released_product($filter){
        $filter['release_time|sthan']=time();
        $filter['begin_time|bthan']=time();
        $filter['status']="true";
        $this->pagedata['beabout_total'] = $this->count($filter);
        //获取参加团购的货品
        $special_goods = $this->mdl_special_goods->getList("*",$filter);
        foreach($special_goods as $value){
            $result[] = $this->special_pro->getParams($value);
        }
        return $result;
    }


    function count($filter){
        $total = $this->mdl_special_goods->count($filter);
        return $total;
    }

    function _getProduct($filter){
        $products="";
        if($filter){
            $products = $this->mdl_product->getRow("*",array('product_id'=>$filter));
        }
        return $products;
    }


    function ajax_get_goods(){
        $post = $this->filter_decode($_POST);
        $page = $post['page'] ? $post['page'] : 1;
        $filter = $post['filter'];
        $orderby = $post['orderby'];
        $goodsData = $this->get_product($filter,$page,$orderby);
        if($goodsData){
            $this->pagedata['goodsData'] = $goodsData;
            echo $this->fetch('site/gallery/type/grid.html');
        }
    }

    function filter_decode($params=null,$type_id){
        if(!$params){
            $cookie_filter = $_COOKIE['S']['SPECIAL']['FILTER'];
            if($cookie_filter){
                $tmp_params = explode('&',$cookie_filter);
                foreach($tmp_params as $k=>$v){
                    $arrfilter = explode('=',$v);
                    $f_k = str_replace('[]','',$arrfilter[0]);
                    if($f_k == 'type_id' || $f_k == 'orderby'|| $f_k == 'page'){
                        $params[$f_k] = $arrfilter[1];
                    }else{
                        $params[$f_k][] = $arrfilter[1];
                    }
                }
            }
            if($params['type_id'] != $type_id){
                unset($params);
                $this->set_cookie('S[SPECIAL][FILTER]','nofilter');
            }
        }//end if

        if($params['orderby']){
            $post['orderby'] = $params['orderby'];
            unset($params['orderby']);
        }else{
            $post['orderby'] = 'promotion_price asc';
            unset($params['orderby']);
        }

        if($params['page']){
            $post['page'] = $params['page'];
        }

        $post['filter'] = $params;

        if($type_id){
            $post['filter']['type_id'] = $type_id;
        }
        return $post;
    }

    function set_cookie($name,$value,$expire=false,$path=null){
        if(!$this->cookie_path){
            $this->cookie_path = kernel::base_url().'/';
            #$this->cookie_path = substr(PHP_SELF, 0, strrpos(PHP_SELF, '/')).'/';
            $this->cookie_life =  app::get('starbuy')->getConf('system.cookie.life');
        }
        $this->cookie_life = $this->cookie_life > 0 ? $this->cookie_life : 315360000;
        $expire = $expire === false ? time()+$this->cookie_life : $expire;
        setcookie($name,$value,$expire,$this->cookie_path);
        $_COOKIE[$name] = $value;
    }

    function ajax_remind_save(){
        $remind_mdl = app::get('starbuy')->model('special_remind');
        $remind = $_POST;
        $way = $this->getWay($remind['goal'],$msg);
        if(!$way){
            $this->splash('error',"",$msg,true);
        }
        $product = $this->mdl_product->getRow('name',array('product_id'=>$remind['product_id']));
        $remind['remind_way'] = $way;
        $remind['savetime'] = time();
        $remind['goodsname'] = $product['name'];
        $result = $remind_mdl->save($remind);
        if($result){
            $url = $this->gen_url(array('app'=>'starbuy', 'ctl'=>'site_team','act'=>'index','arg0'=>$remind['product_id'],'arg1'=>$remind['type_id']));
            $this->splash('success','','订阅成功',true);
        }else{
            $this->splash('error','',"订阅失败",true);
        }
    }




    /*
     * 获取提醒方式(邮箱，手机号码、站内信)
     *
     * @params $login_account 登录账号
     * @return $account_type
     */
    public function getWay($remind_way,&$msg){

        $way = "msgbox";
        if($remind_way && strpos($remind_way,'@')){
            if(!preg_match('/^(?:[a-z\d]+[_\-\+\.]?)*[a-z\d]+@(?:([a-z\d]+\-?)*[a-z\d]+\.)+([a-z]{2,})+$/i',trim($remind_way)) ){
                $msg = app::get('starbuy')->_('邮件格式不正确');
                return false;
            }
            $way = 'email';
        }elseif(preg_match("/^1[34578]{1}[0-9]{9}$/",$remind_way)){
            $way = 'sms';
        }elseif($remind_way){
            $msg = app::get('starbuy')->_('请输入正确邮箱或手机号码');
            return false;
        }
        return $way;
    }

    /*
     * 团购详情页面弹出开售提醒页面
     */

    function remind_url(){
        $get = $this->_request->get_params();
        $filter['product_id'] = $get[0];
        $filter['type_id'] = $get[1];
        $special_goods = $this->mdl_special_goods->getRow("begin_time,remind_time,remind_way,product_id",$filter);
        if(in_array('email',$special_goods['remind_way']) && !in_array('sms',$special_goods['remind_way'])){
            $listpro['email_remind'] = true;
        }elseif(in_array('sms',$special_goods['remind_way']) && !in_array('email',$special_goods['remind_way'])){
            $listpro['sms_remind'] = true;
        }elseif(in_array('email',$special_goods['remind_way']) && in_array('sms',$special_goods['remind_way'])){
            $listpro['all_remind'] = true;
        }else{
            $listpro['msgbox_remind'] = true;
        }
        $this->pagedata['product_id'] = $filter['product_id'];
        $this->pagedata['type_id'] = $filter['type_id'];
        $this->pagedata['remind_time'] = strtotime("-".$special_goods['remind_time']." hour",$special_goods['begin_time']);//$special_goods['begin_time'];
        $this->pagedata['begin_time'] = $special_goods['begin_time'];
        $this->pagedata['member_id'] = ($this->userObject->get_member_id()) ? ($this->userObject->get_member_id()) : "0";
        $this->pagedata['remind_type'] = $listpro;
        echo $this->fetch('site/product/remind.html');
    }

    /*
     *保存订阅提醒信息
     *@POST 订购信息
     */
    function save_remind(){
        $remind_mdl = app::get('starbuy')->model('special_remind');
        $remind = $_POST;
        $way = $this->getWay($remind['goal'],$msg);
        if(!$way){
            $this->splash('error',"",$msg,true);
        }
        $product = $this->mdl_product->getRow('name',array('product_id'=>$remind['product_id']));
        $remind['remind_way'] = $way;
        $remind['savetime'] = time();
        $remind['goodsname'] = $product['name'];
        $result = $remind_mdl->save($remind);
        if($result){
            $url = $this->gen_url(array('app'=>'starbuy', 'ctl'=>'site_team','act'=>'index','arg0'=>$remind['product_id'],'arg1'=>$remind['type_id']));
            $this->splash('success',$url,'订阅成功',true);
        }else{
            $this->splash('error',null,"订阅失败",true);
        }
    }

    function getNowTime(){
        $timenow['timeNow'] = time();
        $timenow = json_encode($timenow);
        echo $timenow;
    }

    function get_best_list(){
        $page = $_POST['page'] ? $_POST['page'] : 1;
        $limit = $_POST['limit'] ? $_POST['limit'] : 5;
        $adModel = app::get('mobileapi')->model('sales_ads');
        $res = $adModel->getlist('ad_name,ad_img,ad_url,ordernum',array('url_type'=>'goods'),($page-1)*$limit,$limit,'ordernum asc');
        $returnData = array();
        $i = 0;
        $flag = true;
        foreach($res as &$v){
            $v['img'] = kernel::single('base_storager')->image_path($v['ad_img'],'m');
            if($v['ordernum']%2){
                $returnData[$i] = $v;
            }else{
                $returnData[$i][] = $v;
                if(count($returnData[$i]) < 2){
                    $flag = false;
                }
            }
            if($flag)
                $i++;
        }
        return $returnData;
    }

    function get_page_list(){
        $page = $_POST['page'] ? $_POST['page'] : 1;
        $limit = $_POST['limit'] ? $_POST['limit'] : 5;
        $type_id = $_POST['type_id'] == 2 ? 2 : 1;
        $clist = '';
        if($type_id == 2){
            $clist = $this->get_coupon();
        }

        $sgModel = app::get('mobileapi')->model('sales_goods');
        $res = $sgModel->getRow('name,description,conditions',array('rule_id'=>$type_id));
        $gids = explode(',',$res['conditions']['goods_select']);
        $goodsList = $this->mdl_goods->getList('buy_count,goods_id,name,price,store,cat_id,image_default_id',array('goods_id',$gids),($page-1)*$limit,$limit);

        $return_data['images'] = kernel::single('base_storager')->image_path($res['description'],'m');
        $return_data['couponList'] = $clist;
        $return_data['title'] = $res['name'];
        foreach($goodsList as &$v){
            $v['img'] = kernel::single('base_storager')->image_path($v['image_default_id'],'m');
        }
        $return_data['goods'] = $goodsList;

        return $return_data;

    }

    function get_coupon(){
        $pageLimit = 3;
        $oExchangeCoupon = kernel::single('b2c_coupon_mem');
        if ($aExchange = $oExchangeCoupon->get_list()) {
            $userObject = kernel::single('b2c_user_object');
            $member = $userObject->get_current_member();
            foreach ($aExchange as $k => $item) {
                $member_lvs = explode(',',$item['time']['member_lv_ids']);
                if (!in_array($member['member_lv'],(array)$member_lvs)) {
                    unset($aExchange[$k]);
                    continue;
                }
            }

            return $aExchange;
        }
        return false;
    }

    function add_coupon($param=array()) {
        $prefix = $this->cutstr($param['cpnsId'], 2);
        if(in_array($prefix,array('VA','VB','VC'))){
            $cpnsId = preg_replace('/^VA|VB|VC/', "A", $param['cpnsId'], 1);
        }else{
            $cpnsId = $param['cpnsId'];
        }
        if(!$cpnsId)
            kernel::single('base_rpc_service')->send_user_error('', '未找到优惠卷');
        //积分设置的用途
        $oExchangeCoupon = kernel::single('b2c_coupon_mem');
        $userObject = kernel::single('b2c_user_object');
        $membersData = $userObject->get_current_member();
        $memberId = intval($membersData['member_id']);//会员id号
        if($memberId){
            $cur_coupon_nums = app::get('b2c')->model('member_coupon')->count(array('cpns_id'=>$cpnsId,'member_id'=>$memberId));
            $coupons = app::get('b2c')->model('coupons');
            $cur_coupon = $coupons->dump($cpnsId);
            if($cur_coupon['cpns_max_num'] > 0 ){  //兼容老数据处理老数据还是无限制兑换
                if($cur_coupon_nums >= $cur_coupon['cpns_max_num']){
                    kernel::single('base_rpc_service')->send_user_error('', '您的兑换次数已达上限！');
                }
            }
            if($membersData['point'] < $cur_coupon['cpns_point']){
                kernel::single('base_rpc_service')->send_user_error('', '您的积分不足！');
            }
            $res = $oExchangeCoupon->exchange($cpnsId,$memberId,$membersData['point'],$params);
            if($res){
                $cpns_point = $params['cpns_point'];
                if($cpns_point > 0){
                    $member_point = app::get('b2c')->model('member_point');
                    if(!$member_point->change_point($this->member['member_id'],-$cpns_point,$msg,'exchange_coupon',2,$memberId,$memberId,'exchange')) {
                        $oExchangeCoupon->exchange_delete($params);
                        kernel::single('base_rpc_service')->send_user_error('','兑换失败');
                    }
                }
                return array('ok' => true);
            }
        }else{
            kernel::single('base_rpc_service')->send_user_error('','没有登录');
        }
        kernel::single('base_rpc_service')->send_user_error('','积分不足或兑换购物券无效');
    }
    function cutstr($str,$cutleng)
    {
        $str = $str; //要截取的字符串
        $cutleng = $cutleng; //要截取的长度
        $strleng = strlen($str); //字符串长度
        if($cutleng>$strleng)return $str;//字符串长度小于规定字数时,返回字符串本身
        $notchinanum = 0; //初始不是汉字的字符数
        for($i=0;$i<$cutleng;$i++)
        {
        if(ord(substr($str,$i,1))<=128)
        {
        $notchinanum++;
        }
        }
        if(($cutleng%2==1)&&($notchinanum%2==0)) //如果要截取奇数个字符，所要截取长度范围内的字符必须含奇数个非汉字，否则截取的长度加一
        {
        $cutleng++;
        }
        if(($cutleng%2==0)&&($notchinanum%2==1)) //如果要截取偶数个字符，所要截取长度范围内的字符必须含偶数个非汉字，否则截取的长度加一
        {
        $cutleng++;
        }
        return substr($str,0,$cutleng);
    }
}
